package com.mgy.shardingjdbc.test.service.notepad;


import com.mgy.db.TableRouter;
import com.mgy.shardingjdbc.test.dao.mapper.notepad.INotepadDao;
import com.mgy.shardingjdbc.test.dao.mapper.notepad.ITagDao;
import com.mgy.shardingjdbc.test.domain.notepad.Notepad;
import com.mgy.shardingjdbc.test.domain.notepad.Tag;
import com.mgy.shardingjdbc.test.domain.notepad.TagAndNotepad;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 测试
 */
@Service
public class NotepadService {
    @Autowired
    private INotepadDao notepadDao;
    @Autowired
    private ITagDao tagDao;

    public void add(Notepad notepad) {
        notepadDao.add(notepad);
    }

    public Notepad getOne(Integer id) {
        return notepadDao.getByKey(id, "notepad", 1, 1);
    }


    public List<TagAndNotepad> getTagAndNotepad(Long id) {
        List<TableRouter> tableRouters = new ArrayList<>();
        TableRouter stockTable = new TableRouter();
        stockTable.setLogicTable("notepad");
        stockTable.setDbNo(1);
        stockTable.setTableNo(1);
        tableRouters.add(stockTable);

        TableRouter stockTable2 = new TableRouter();
        stockTable2.setLogicTable("tag");
        stockTable2.setDbNo(1);
        stockTable2.setTableNo(0);
        tableRouters.add(stockTable2);

        return notepadDao.getTagAndNotepad(id, tableRouters);
    }

    //@ShardingTransactionType(TransactionType.XA)
    @Transactional(rollbackFor = RuntimeException.class)
    public void addNotepadAndTag(Notepad notepad, Tag tag) {
        TableRouter notepadTable = new TableRouter();
        notepadTable.setLogicTable("notepad");
        notepadTable.setDbNo(1);
        notepadTable.setTableNo(0);

        TableRouter tagTable = new TableRouter();
        tagTable.setLogicTable("tag");
        tagTable.setDbNo(3);
        tagTable.setTableNo(0);

        notepadDao.add(notepad, notepadTable);
        tagDao.add(tag, tagTable);
        throw new RuntimeException("回滚");
    }


    public Notepad getOne2(Integer id) {
        return notepadDao.getByKey(id, null, null, null);
    }
}
